package com.heima.verify.service.impl;

import com.baidu.aip.util.Base64Util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.heima.verify.utils.HttpUtil;
import org.springframework.beans.factory.annotation.Value;
import okhttp3.*;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.time.LocalDateTime;
import java.net.URLEncoder;
import java.util.Map;

@Component
public class VerifyMaterialServiceImpl {
    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    private static LocalDateTime BEGIN = null;

    private static String TOKEN = null;

    @Value("${baidu.api}")
    public String api;

    @Value("${baidu.secret}")
    public String secret;


    public void demo() {
        System.out.println(api);
        System.out.println(secret);
    }

    /**
     * 获取token
     *
     * @return
     */
//    @Override
    public String getToken() {
        try {
            if (BEGIN == null || Duration.between(BEGIN, LocalDateTime.now()).toDays() >= 30) {
                MediaType mediaType = MediaType.parse("application/json");
                RequestBody body = RequestBody.create(mediaType, "");
                Request request = new Request.Builder()
                        .url("https://aip.baidubce.com/oauth/2.0/token?client_id=e1my6sEEGelkhqLPnaf07vtU&client_secret=WuPm3jGPW5yDqwz1OpNsF09UoyzFmK2V&grant_type=client_credentials")
                        .method("POST", body)
                        .addHeader("Content-Type", "application/json")
                        .addHeader("Accept", "application/json")
                        .build();
                Response response = HTTP_CLIENT.newCall(request).execute();
                BEGIN = LocalDateTime.now();
                JSONObject jsonObject = JSON.parseObject(response.body().string());
                TOKEN = (String) jsonObject.get("access_token");
                return TOKEN;
            } else {
                return TOKEN;
            }
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 校验文本
     * @param text
     * @return
     */
//    @Override
    public Map VerifyText(String text) {
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined";
        try {
            String param = "text=" + URLEncoder.encode(text, "utf-8");
            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = getToken();
            String result = HttpUtil.post(url, accessToken, param);
            Map map = JSON.parseObject(result, Map.class);
            return map;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 校验图片
     *
     * @param images
     * @return
     */
//    @Override
    public Map VerifyImage(byte[] images) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined";
        try {
            // 本地文件路径
            String imgStr = Base64Util.encode(images);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            String param = "image=" + imgParam;
            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = getToken();
            String result = HttpUtil.post(url, accessToken, param);
            Map map = JSON.parseObject(result, Map.class);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
